package mediator;

import entity.EEntity;
import foundation.FDataStreamReader;
import java.util.Observable;
import java.util.Observer;

public class MDataStreamHandler extends Observable implements Observer {
	private EEntity eEntity;
	private FDataStreamReader fDataStreamReader;
	private MFileCommunication mFileCommunication;
	
	public MDataStreamHandler(EEntity eEntity, 
			MFileCommunication mFileCommunication, String address, int port) {
		this.eEntity = eEntity;
		this.mFileCommunication = mFileCommunication;
        
        fDataStreamReader = new FDataStreamReader(address, port);
        fDataStreamReader.addObserver(this);
	}
	
	public void startStreaming(String host, int port)
    {
        fDataStreamReader.stop();
        fDataStreamReader = new FDataStreamReader(fDataStreamReader, host, port);
        fDataStreamReader.addObserver(this);
        new Thread(fDataStreamReader).start();
	}
    
    public void stopStreaming()
    {
        fDataStreamReader.stop();
    }
        
	public void addStatusObserver(Observer obs) {
		fDataStreamReader.addStatusObserver(obs);
	}
	
	public void deleteStatusObserver(Observer obs) {
		fDataStreamReader.deleteStatusObserver(obs);
	}

	@Override
	public void update(Observable obs, Object data)
    {
        if (data instanceof byte[]) {
            eEntity.updateRegisterData((byte[]) data);
            setChanged();
            notifyObservers();
        } else if (data instanceof String) {
            mFileCommunication.addError((String) data);
        }
	}
	
}
